﻿using System.IO;
using ClassDAL.Entities;
using CodeGenBL.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using FluentNHibernate.Automapping;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Mapping;
using NHibernate.Tool.hbm2ddl;
using ProjectDAL;
using ProjectDAL.Entities;
using ProjectDAL.Models;


namespace CodeGenBL
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "ProjectBL" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select ProjectBL.svc or ProjectBL.svc.cs at the Solution Explorer and start debugging.
    public class ProjectBL : IProjectBL
    {
        public ISession Session;
        ISessionFactory SessionFactory;

        public ProjectBL()
        {
            System.Configuration.AppSettingsReader appReader = new System.Configuration.AppSettingsReader();
            string connectionString = Convert.ToString(appReader.GetValue("connectionString", typeof(string)));
            string mappingScriptPath = AppDomain.CurrentDomain.BaseDirectory + "/db_mappings";
            if (!Directory.Exists(mappingScriptPath))
                Directory.CreateDirectory(mappingScriptPath);

            SessionFactory = Fluently.Configure()
                .Database(
                    MsSqlConfiguration.MsSql2008
                    .ConnectionString(@connectionString))
                    .Mappings(x => x.AutoMappings.Add(AutoMap.AssemblyOf<User>().Where(t => t.Namespace.EndsWith("Entities"))).ExportTo(@mappingScriptPath))
                    //.ExposeConfiguration(BuildSchema) // ********** ใช้ครั้งแรกเท่านั้น (กรณียังไม่มี Table)
                    .BuildSessionFactory();
            Session = SessionFactory.OpenSession();
        }
        private static void BuildSchema(Configuration config)
        {
            new SchemaExport(config).Create(false, true);
        }


        public ActionResultDto<int> AddProject(ProjectDto projectDto)
        {
            ActionResultDto<int> result=new ActionResultDto<int>();
            using (Session.BeginTransaction())
            {
                try
                {
                    var project = projectDto.TransformToProjectModel();
                    IProjectDAL obj = new ProjectDAL.ProjectDAL(Session);
                    result.Data = obj.AddProject(project);
                    Session.Transaction.Commit();
                    result.Status = true;
                }
                catch (Exception ex)
                {
                    Session.Transaction.Rollback();
                    result.Status = false;
                    result.ErrorMessage = ex.Message;
                }
            }

            return result;
        }

        public ActionResultDto<int> AddUser(AddUserDto addUserDto)
        {
           ActionResultDto<int> result=new ActionResultDto<int>();
           var user = addUserDto.TransformToUserModel();
            using (Session.BeginTransaction())
            {
                try
                {
                    IProjectDAL obj = new ProjectDAL.ProjectDAL(Session);
                    user.CreateDate = DateTime.Now;
                    user.LastLogin = DateTime.Now;
                    result.Data = obj.AddUser(user);
                    Session.Transaction.Commit();
                    result.Status = true;
                }
                catch (Exception ex)
                {
                    Session.Transaction.Rollback();
                    result.Status = false;
                    result.ErrorMessage = ex.Message;
                }
            }

            return result;
        }

        public ActionResultDto<List<ProjectHeaderDto>> GetProjectNameByUserId(UserPkDto userPKDto)
        {
            ActionResultDto<List<ProjectHeaderDto>> result = new ActionResultDto<List<ProjectHeaderDto>>();
            try
            {
                IProjectDAL obj = new ProjectDAL.ProjectDAL(Session);
                User objUser = obj.GetUser(new UserSearchCriteria { Id = userPKDto.UserId });
                if (objUser != null)
                {
                    result.Status = true;
                    result.Data = new List<ProjectHeaderDto>();
                    if (objUser.Projects.Count > 0)
                    {
                        foreach (var item in objUser.Projects)
                        {
                            result.Data.Add(new ProjectHeaderDto
                            {
                                Id = item.Id,
                                Name = item.Name
                            });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result.Status = false;
                result.ErrorMessage = ex.Message;
            }
            return result;
            
        }

        public ActionResultDto<UserDto> Login(LoginDto loginDto)
        {
            ActionResultDto<UserDto> result = new ActionResultDto<UserDto>();
            try
            {
                IProjectDAL obj = new ProjectDAL.ProjectDAL(Session);
                UserSearchCriteria search = null;
                if (loginDto != null)
                {
                    search = new UserSearchCriteria()
                    {
                        UserName = loginDto.UserName,
                        Password = loginDto.Password
                    };
                }
                User user = obj.GetUser(search);
                if (user != null)
                {
                    result.Status = true;
                    result.Data = new UserDto()
                    {
                      Id = user.Id,
                      UserName = user.UserName,
                      Password = user.Password,
                      CreateDate = user.CreateDate,
                      LastLogin = user.LastLogin

                    };
                }
              
            }
            catch (Exception ex)
            {

                result.Status = false;
                result.ErrorMessage = ex.Message;
            }
            return result;
           
        }

        public ActionResultDto<ProjectDto> GetProject(ProjectPKDto ptojectPkDto)
        {
            ActionResultDto<ProjectDto> result = new ActionResultDto<ProjectDto>();
            try
            {
                IProjectDAL obj = new ProjectDAL.ProjectDAL(Session);
                ProjectPk projectPk = null;
                if (ptojectPkDto != null)
                {
                    projectPk = new ProjectPk
                    {
                         Id = ptojectPkDto.ProjectId
                    };
                }
                Project project = obj.GetProjectById(projectPk);
                if (project != null)
                {
                    result.Status = true;
                    result.Data = new ProjectDto()
                    {
                        CreateTime = project.CreateDate,
                        UserId = project.User.Id,
                        DbName = project.DbName,
                        DbPassword = project.DbPassword,
                        DbServerName = project.DbServerName,
                        DbUserName = project.DbUserName,
                        Id = project.Id,
                        LastUpdate = project.LastUpdate,
                        Name = project.Name,
                        Platform = project.Platform,
                        StyleId = project.StyleId,
                        Version = project.Version
                    };
                }

            }
            catch (Exception ex)
            {

                result.Status = false;
                result.ErrorMessage = ex.Message;
            }
            return result;
        }
    }
}
